package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"shang/models"
)

type BarrageController struct {
	beego.Controller
}
type BarrageMsg struct {
	EpisodesId int    `json:"episodes_id" form:"episodes_id"` //剧集
	Sss        int    `json:"sss" form:"sss"`                 //存放的是视频播放的秒数（30分钟就是1800秒）
	Content    string `json:"content" form:"content"`         //弹幕内容
	UserId     int    `json:"user_id" form:"user_id"`         //用户表ID
	VideoId    int    `json:"video_id" form:"video_id"`       //视频ID
}

func (b *BarrageController) CreateBarrage() {
	upgrade := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrade.Upgrade(b.Ctx.ResponseWriter, b.Ctx.Request, nil)
	if err != nil {
		log.Println("websocket连接失败", err)
		return
	}
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			conn.WriteMessage(websocket.TextMessage, []byte("websocket接收消息失败"))
		}
		var msg BarrageMsg
		json.Unmarshal(message, &msg)
		_, err = models.CreateBarrage(models.Barrage{
			Content:    msg.Content,
			UserId:     msg.UserId,
			Sss:        msg.Sss,
			EpisodesId: msg.EpisodesId,
			VideoId:    msg.VideoId,
		})
		if err != nil {
			conn.WriteMessage(websocket.TextMessage, []byte("发送失败"))
		}
		conn.WriteMessage(websocket.TextMessage, []byte("发送成功"))
	}
}
func (b *BarrageController) ShowBarrage() {
	upgrade := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrade.Upgrade(b.Ctx.ResponseWriter, b.Ctx.Request, nil)
	if err != nil {
		log.Println("websocket连接失败", err)
		return
	}
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			goto ERR
		}
		var msg BarrageMsg
		json.Unmarshal(message, &msg)
		endTime := msg.Sss + 5
		barrage, err := models.GetBarrage(msg.VideoId, msg.EpisodesId, msg.Sss, endTime)
		log.Println(barrage, err)
		barrageMarshal, err := json.Marshal(barrage)
		if err != nil {
			goto ERR
		}
		conn.WriteMessage(websocket.TextMessage, barrageMarshal)
	}
ERR:
	defer conn.Close()
}
